using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

namespace AspNetThemesExtensions
{
    /// <summary>
    /// Virtual path provider that catches theme directories with name "/App_Themes/X_InheritsFrom_Y" and applies special logic to support inheritance
    /// </summary>
    public class ThemeVirtualPathProvider : System.Web.Hosting.VirtualPathProvider
    {
        private const string MagicName = "_InheritsFrom_";

        public override bool FileExists(string virtualPath)
        {
            if (IsExtendedTheme(virtualPath))
                return base.FileExists(GetBaseThemePath(virtualPath)) || base.FileExists(virtualPath);
            else
                return base.FileExists(virtualPath);
        }

        private static string GetBaseThemePath(string virtualPath)
        {
            return "/App_Themes/" + virtualPath.Substring(virtualPath.IndexOf(MagicName) + MagicName.Length);
        }

        private bool IsExtendedTheme(string virtualPath)
        {
            return virtualPath.ToUpper().StartsWith("/APP_THEMES/") && virtualPath.Contains(MagicName);
        }

        public override bool DirectoryExists(string virtualPath)
        {
            if (IsExtendedTheme(virtualPath))
                return base.DirectoryExists(GetBaseThemePath(virtualPath)) || Directory.Exists(HttpContext.Current.Server.MapPath("~" + virtualPath));
            else
                return base.DirectoryExists(virtualPath);
        }

        public override System.Web.Hosting.VirtualDirectory GetDirectory(string virtualDir)
        {
            if (IsExtendedTheme(virtualDir))
                return new ThemeVirtualDirectory(virtualDir,base.GetDirectory(GetBaseThemePath(virtualDir)));
            else
                return base.GetDirectory(virtualDir);
        }

        public override System.Web.Hosting.VirtualFile GetFile(string virtualPath)
        {
            string fullPath = HttpContext.Current.Server.MapPath("~" + virtualPath);

            if (IsExtendedTheme(virtualPath))
                return new ThemeVirtualFile(virtualPath,GetBaseThemePath(virtualPath));
            else
                return Previous.GetFile(virtualPath);
        }

        public override System.Web.Caching.CacheDependency GetCacheDependency(string virtualPath, System.Collections.IEnumerable virtualPathDependencies, DateTime utcStart)
        {
            return new System.Web.Caching.CacheDependency(HttpContext.Current.Server.MapPath("~/Web.config"));
        }
    }
}
